package com.watch.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.watch.system.common.result.PageResult;
import com.watch.system.common.result.Result;
import com.watch.system.common.util.ExcelUtils;
import com.watch.system.model.entity.CarAd;
import com.watch.system.model.form.AdForm;
import com.watch.system.model.query.CarAdPageQuery;
import com.watch.system.model.vo.*;
import com.watch.system.plugin.easyexcel.AdImportListener;
import com.watch.system.service.CarAdService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 广告管理
 *
 * @author gmli
 * @since 2024/1/26
 */
@Tag(name = "广告维护接口")
@RestController
@RequestMapping("/api/car/ad")
@RequiredArgsConstructor
public class AdController {

    private final CarAdService carAdService;

    @Operation(summary = "广告分页列表")
    @GetMapping("/page")
    public PageResult<CarAdPageVO> getAdPage(
            @ParameterObject CarAdPageQuery queryParams
    ) {
        IPage<CarAdPageVO> result = carAdService.getAdPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "修改广告")
    @PutMapping(value = "/updateAd")
    public Result updateAd(@RequestBody @Validated AdForm adForm) {
        boolean result = carAdService.updateAd(adForm);
        return Result.judge(result);
    }

    @Operation(summary = "修改广告状态")
    @PatchMapping(value = "/{userId}/status")
    public Result updateUserStatus(@Parameter(description = "广告ID") @PathVariable Integer adId,
            @Parameter(description = "广告状态(1:启用;0:禁用)") @RequestParam Integer status) {
        boolean result = carAdService.update(new LambdaUpdateWrapper<CarAd>()
                .eq(CarAd::getAdId, adId)
                .set(CarAd::getStatus, status)
        );
        return Result.judge(result);
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("/{id}")

    public Result deleteAd(@Parameter(description ="广告ID，多个以英文(,)分割")@PathVariable("id") String id) {
        boolean result = carAdService.deleteAd(id);
        return Result.judge(result);
    }

    @Operation(summary = "广告导入模板下载")
    @GetMapping("/templateAd")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "广告模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "导入广告")
    @PostMapping("/impAd")
    public Result imporAd(MultipartFile file) throws IOException {
        AdImportListener listener = new AdImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), CarAdImportVO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出广告")
    @GetMapping("/expAd")
    public void exportAd(CarAdPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "广告数据.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<CarAdExportVO> exportUserList = carAdService.listExportAds(queryParams);
        EasyExcel.write(response.getOutputStream(), CarAdExportVO.class).sheet("广告列表")
                .doWrite(exportUserList);
    }
}
